package com.ys.otms.services.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ys.otms.dao.IDeductionsDao;
import com.ys.otms.dao.IFindShipFeedbackDao;
import com.ys.otms.dao.IShipDao;
import com.ys.otms.dto.*;
import com.ys.otms.services.IShipServices;
import com.ys.otms.utils.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.*;

@Service
public class ShipServiceImpl implements IShipServices {

    @Autowired
    private IShipDao iShipDao;
    @Autowired
    private IDeductionsDao iDeductionsDao;

    private static Logger logger = LoggerFactory.getLogger(ShipServiceImpl.class);


    static Map<Integer,String> shipState = new HashMap<>();
    static {
        shipState.put(0,"在航（主机推)");
        shipState.put(1,"锚泊");
        shipState.put(2,"失控");
        shipState.put(3,"操纵受限");
        shipState.put(4,"吃水受限");
        shipState.put(5,"靠泊");
        shipState.put(6,"搁浅");
        shipState.put(7,"捕捞作业");
        shipState.put(8,"靠帆船提供动力");
        shipState.put(9,"为将来 HSC 航行状态修正保留");
        shipState.put(10,"为将来 WIG 航行状态修正保留");
    }



    /**
     * 查询全部自有运力（ren_zheng_state 是否认证：0未认证，1认证;monitoring：监控：0未监控，1监控）
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject selectAllShips(HttpServletRequest request) throws Exception {
        JSONObject obj = JsonUtil.getJSONObject(request);
        logger.info("ShipServiceImpl selectAllShips start obj{}",obj);
        String page =JsonUtil.getJSONObjectString(obj,"page");
        String limit = JsonUtil.getJSONObjectString(obj,"limit");
        String shipName = JsonUtil.getJSONObjectString(obj,"shipName");
        String rzState = JsonUtil.getJSONObjectString(obj,"rzState");
        String monitoring =JsonUtil.getJSONObjectString(obj,"monitoring");
        String startTon = JsonUtil.getJSONObjectString(obj,"startTon");
        String endTon = JsonUtil.getJSONObjectString(obj,"endTon");
        ParamDto param = new ParamDto();
        if (StringUtil.isNotEmpty(shipName)){
            param.setShipName(shipName);
        }
        if (StringUtil.isNotEmpty(rzState)){
            param.setRzState(Integer.parseInt(rzState));
        }
        if (StringUtil.isNotEmpty(monitoring)){
            param.setMonitoring(Integer.parseInt(monitoring));
        }
        if (StringUtil.isNotEmpty(startTon)){
            param.setMinTonnage(Double.parseDouble(startTon));
        }
        if (StringUtil.isNotEmpty(endTon)){
            param.setMaxTonnage(Double.parseDouble(endTon));
        }
        param.setUsStatus(1);
        param.setEndTime(new Timestamp((new Date()).getTime()));
        Integer companyId =  Integer.parseInt((String) request.getSession().getAttribute("SESSION_COMPANY_ID"));
        param.setUserId(companyId);
        PageHelper.startPage(Integer.parseInt(page),Integer.parseInt(limit));
        List<ShipInfoDto> shipInfoDtoList = iShipDao.selectAllShipsQuery(param);
        JSONObject jsonObject = new JSONObject();
        PageInfo pageInfo = new PageInfo(shipInfoDtoList);
        jsonObject.put("pageInfo",pageInfo);
        jsonObject.put("shipsList",shipInfoDtoList);
        jsonObject.put("SUCCESS",true);
        return jsonObject;
    }

    /**
     * 删除自由运力
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject deleteShipsByShipid(HttpServletRequest request) throws Exception {
        JSONObject obj =JsonUtil.getJSONObject(request);
        logger.info("ShipServiceImpl deleteShipsByShipid start obj{}",obj);
        String shipid = JsonUtil.getJSONObjectString(obj,"shipId");
        ParamDto param = new ParamDto();
        JSONObject jsonObject = new JSONObject();
        if (StringUtil.isNotEmpty(shipid)){
            param.setShipId(Integer.parseInt(shipid));
            param.setUsStatus(0);
            param.setUserId(Integer.parseInt((String) request.getSession().getAttribute("SESSION_COMPANY_ID")));
            iShipDao.deleteShipsByShipid(param);
            jsonObject.put("SUCCESS",true);
            jsonObject.put("MSG","删除成功！");
        }else{
            jsonObject.put("SUCCESS",false);
            jsonObject.put("MSG","请选中船舶！");
        }
        return jsonObject;
    }

    @Override
    public JSONObject queryRegionShip(HttpServletRequest request) throws Exception {
        JSONObject obj =JsonUtil.getJSONObject(request);
        logger.info("ShipServiceImpl deleteShipsByShipid start obj{}",obj);
        List<RegionDto> list = iShipDao.queryRegion(new RegionDto());
        JSONObject retObj = new JSONObject();
        retObj.put("areaList", list);
        retObj.put("SUCCESS",true);
        return retObj;
    }

    @Override
    /**
     * 航行日志查询
     */
    public JSONObject selectShipSailLog(HttpServletRequest request) throws Exception{
        JSONObject obj = JsonUtil.getJSONObject(request);
        String begin=  DateUtil.date2String(DateUtil.offsetDay(new Date(),-7),"yyyy-MM-dd HH:mm:ss");
        String end = DateUtil.date2String(new Date(),"yyyy-MM-dd HH:mm:ss");
        obj.put("begin",begin);
        obj.put("end",end);
        logger.info("ShipServiceImpl selectShipSailLog start obj{}",obj);
        JSONObject objRet = ShipXyAPIUtil.getPortOfCallByShip(obj);
        if (null == objRet) {
            return null;
        }
        JSONArray jsonArray = objRet.getJSONArray("records");
        JSONArray retJsonArray = new JSONArray();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            if (StringUtil.isNotEmpty(object.getString("ata"))) {
                object.put("arrive",0);
                object.put("portname_cn",JsonUtil.getJSONObjectString(object,"portname_cn"));
                object.put("time",object.getString("ata"));
                retJsonArray.add(object);
            }

            if (StringUtil.isNotEmpty(object.getString("atd"))) {
                object.put("arrive",1);
                object.put("portname_cn",JsonUtil.getJSONObjectString(object,"portname_cn"));
                object.put("time",object.getString("atd"));
                retJsonArray.add(object);
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("records",retJsonArray);
        jsonObject.put("SUCCESS",true);
        return jsonObject;
    }

    @Override
    public JSONObject uploadShipInfo(HttpServletRequest request,JSONObject obj) throws Exception {
        logger.info("ShipServiceImpl uploadShipInfo start obj{}",obj);
        JSONObject jsonObject1= new JSONObject();
        JSONObject jsonObject = excelUtil.readExcel(obj);
        int rowCounts =0;
        if(StringUtil.isNotEmpty(JsonUtil.getJSONObjectString(jsonObject,"countRow"))){
            rowCounts =Integer.parseInt(JsonUtil.getJSONObjectString(jsonObject,"countRow"));
        }
        JSONArray jsonArray = null;
        if (JsonUtil.getJSONArray(jsonObject,"shipLists") !=null){
            jsonArray = JsonUtil.getJSONArray(jsonObject,"shipLists");
        }
        //上传的船舶在数据库中是有的
        List<ShipInfoDto> shipInfoDtoList = new ArrayList<>();
        //上传的船舶在数据库中是没有的
        List<ShipInfoDto> shipInfoDtoList1 = new ArrayList<>();
        //将船舶与船主绑定在一起
        List<ShipInfoDto> shipInfoDtoList2 = new ArrayList<>();
        List<ShipInfoDto> shipInfoDtoListo = new ArrayList<>();
        //返回的船舶集合
        List<ShipInfoDto> shipList = new ArrayList<>();
        ShipInfoDto shipInfoDto = null;
        for (int i=0;i<jsonArray.size();i++){
            JSONObject onwerObj = (JSONObject) jsonArray.get(i);
            shipInfoDto = new ShipInfoDto();
            shipInfoDto.setShipName(onwerObj.getString("shipName"));
            shipInfoDto.setPhoneNum(onwerObj.getString("phoneNum"));
            shipInfoDto.setTonnage(Double.parseDouble(onwerObj.getString("tonnage")));
            shipInfoDtoList.add(shipInfoDto);
        }
        //根据船名查询所有船舶信息
        List<ShipInfoDto> shipInfoDtos = iShipDao.selectShipInfoByShipName(shipInfoDtoList);
        if (shipInfoDtos.size()>0){
            for (int j = 0; j < jsonArray.size(); j++) {
                JSONObject onwerObj = (JSONObject) jsonArray.get(j);
                for (int k = 0; k <shipInfoDtos.size() ; k++) {
                    if (onwerObj.getString("shipName").equals(shipInfoDtos.get(k).getShipName())){
                        break;
                    }
                    if (k==shipInfoDtos.size()-1){
                        shipInfoDto = new ShipInfoDto();
                        shipInfoDto.setShipName(onwerObj.getString("shipName"));
                        shipInfoDto.setPhoneNum(onwerObj.getString("phoneNum"));
                        shipInfoDto.setTonnage(Double.parseDouble(onwerObj.getString("tonnage")));
                        shipInfoDtoList1.add(shipInfoDto);
                    }
                }
            }

            if (shipInfoDtoList1.size()==0){
                for (int i = 0; i < shipInfoDtos.size(); i++) {
                    shipInfoDto = new ShipInfoDto();
                    shipInfoDto.setCompanyId(Integer.parseInt((String) request.getSession().getAttribute("SESSION_COMPANY_ID")));
                    //shipInfoDto.setCompanyId(1);
                    shipInfoDto.setShipId(shipInfoDtos.get(i).getShipId());
                    shipList.add(shipInfoDto);
                }

                jsonObject1.put("shipList",shipList);
                jsonObject1.put("shipListCount",shipList.size());
                jsonObject1.put("rowCounts",rowCounts);
                return jsonObject1;

            }else{
                //判断数据库中有没有该船主
                List<ShipOwnerDto> shipOwnerDtoList = iShipDao.selectShipOwnerByPhoneNum(shipInfoDtoList1);
                if (shipOwnerDtoList.size()>0){
                    for (int i = 0; i < shipInfoDtoList1.size(); i++) {
                        for (int j = 0; j <shipOwnerDtoList.size() ; j++) {
                            if (shipOwnerDtoList.get(j).getPhoneNum().equals(shipInfoDtoList1.get(i).getPhoneNum())) {
                                break;
                            }
                            if(j==shipOwnerDtoList.size()-1){
                                shipInfoDto = new ShipInfoDto();
                                shipInfoDto.setPhoneNum(shipInfoDtoList1.get(i).getPhoneNum());
                                shipInfoDtoListo.add(shipInfoDto);
                            }
                        }
                    }
                    if (shipInfoDtoListo.size()>0){
                        iShipDao.insertShipOwnerByPhoneNum(shipInfoDtoListo);
                    }
                }else{
                    iShipDao.insertShipOwnerByPhoneNum(shipInfoDtoList1);
                }
                List<ShipOwnerDto> shipOwnerDtoList2 = iShipDao.selectShipOwnerByPhoneNum(shipInfoDtoList1);
                for (int a = 0; a < shipOwnerDtoList2.size(); a++) {
                    for (int b = 0; b < shipInfoDtoList1.size(); b++) {
                        if (shipOwnerDtoList2.get(a).getPhoneNum().equals(shipInfoDtoList1.get(b).getPhoneNum())){
                            shipInfoDto = new ShipInfoDto();
                            shipInfoDto.setShipName(shipInfoDtoList1.get(b).getShipName());
                            shipInfoDto.setTonnage(shipInfoDtoList1.get(b).getTonnage());
                            shipInfoDto.setShipOwnerId(shipOwnerDtoList2.get(a).getId());
                            shipInfoDtoList2.add(shipInfoDto);
                        }
                    }
                }
            }
        }else{
            List<ShipOwnerDto> shipOwnerDtoList = iShipDao.selectShipOwnerByPhoneNum(shipInfoDtoList);
            if (shipOwnerDtoList.size()>0){
                for (int i = 0; i < shipInfoDtoList.size(); i++) {
                    for (int j = 0; j <shipOwnerDtoList.size() ; j++) {
                        if (shipOwnerDtoList.get(j).getPhoneNum().equals(shipInfoDtoList.get(i).getPhoneNum())) {
                            break;
                        }
                        if(j==shipOwnerDtoList.size()-1){
                            shipInfoDto = new ShipInfoDto();
                            shipInfoDto.setPhoneNum(shipInfoDtoList.get(i).getPhoneNum());
                            shipInfoDtoListo.add(shipInfoDto);
                        }
                    }
                }
                if (shipInfoDtoListo.size()>0){
                    iShipDao.insertShipOwnerByPhoneNum(shipInfoDtoListo);
                }
            }else{
                iShipDao.insertShipOwnerByPhoneNum(shipInfoDtoList);
            }
            List<ShipOwnerDto> shipOwnerDtoList2 = iShipDao.selectShipOwnerByPhoneNum(shipInfoDtoList);
            for (int a = 0; a < shipOwnerDtoList2.size(); a++) {
                for (int b = 0; b < shipInfoDtoList.size(); b++) {
                    if (shipOwnerDtoList2.get(a).getPhoneNum().equals(shipInfoDtoList.get(b).getPhoneNum())){
                        shipInfoDto = new ShipInfoDto();
                        shipInfoDto.setShipName(shipInfoDtoList.get(b).getShipName());
                        shipInfoDto.setTonnage(shipInfoDtoList.get(b).getTonnage());
                        shipInfoDto.setShipOwnerId(shipOwnerDtoList2.get(a).getId());
                        shipInfoDtoList2.add(shipInfoDto);
                    }
                }
            }
        }
        iShipDao.insertShipInfoQuery(shipInfoDtoList2);
        List<ShipInfoDto> infoDtos = iShipDao.selectShipInfoByShipName(shipInfoDtoList2);
        for (int i = 0; i < infoDtos.size(); i++) {
            shipInfoDto = new ShipInfoDto();
            shipInfoDto.setCompanyId(Integer.parseInt((String) request.getSession().getAttribute("SESSION_COMPANY_ID")));
            shipInfoDto.setShipId(infoDtos.get(i).getShipId());
            shipList.add(shipInfoDto);
        }
        jsonObject1.put("shipList",shipList);
        jsonObject1.put("shipListCount",shipList.size());
        jsonObject1.put("rowCounts",rowCounts);
        return jsonObject1;
    }


    @Override
    public JSONObject insertShipAndByShipId(HttpServletRequest request,JSONObject obj) throws Exception {
        logger.info("ShipServiceImpl insertShipAndByShipId start obj{}",obj);
        String shipid = JsonUtil.getJSONObjectString(obj,"shipId");
        ParamDto param = new ParamDto();
        JSONObject jsonObject = new JSONObject();
        if (StringUtil.isNotEmpty(shipid)){
            param.setShipId(Integer.parseInt(shipid));
        }
        //   param.setUserId((int)SessionUtil.getAttribute(request,"SESSION_COMPANY_ID"));
        param.setUserId(Integer.parseInt((String) request.getSession().getAttribute("SESSION_COMPANY_ID")));

        iShipDao.insertShipAndByShipId(param);
        jsonObject.put("SUCCESS",true);
        jsonObject.put("MSG","新增成功！");
        return jsonObject;
    }

    @Override
    public JSONObject selectAllShipsByShipName(HttpServletRequest request) throws Exception {
        JSONObject obj = JsonUtil.getJSONObject(request);
        logger.info("ShipServiceImpl selectAllShipsByShipName start obj{}",obj);
        String shipName = JsonUtil.getJSONObjectString(obj,"shipName");
        String mmsi = JsonUtil.getJSONObjectString(obj,"mmsi");
        ParamDto paramDto = new ParamDto();
        JSONObject jsonObject = new JSONObject();
        if (StringUtil.isNotEmpty(shipName)) {
            paramDto.setShipName(shipName);
        }
        if (StringUtil.isNotEmpty(mmsi)){
            paramDto.setMmsi(mmsi);
        }
        paramDto.setUserId(Integer.parseInt((String) request.getSession().getAttribute("SESSION_COMPANY_ID")));
        ShipInfoDto shipInfoDto = iShipDao.selectShipInfoByCompanyId(paramDto);
        if (shipInfoDto == null){
            ShipInfoDto shipInfoDto1 = iShipDao.selectShipInfoByShipNameAndByMmsi(paramDto);
            jsonObject.put("shipInfoDto",shipInfoDto1);
            jsonObject.put("SUCCESS",true);
        }else {
            if (shipInfoDto.getUsStatus()==1){
                jsonObject.put("MSG","该船在自有运力中已存在！");
                jsonObject.put("SUCCESS",false);
            }else{
                jsonObject.put("shipInfoDto",shipInfoDto);
                jsonObject.put("SUCCESS",true);
            }
        }
        return jsonObject;
    }

    @Override
    public JSONObject insertShipInfo(HttpServletRequest request) throws Exception {
        JSONObject obj = JsonUtil.getJSONObject(request);
        logger.info("ShipServiceImpl insertShipInfo start obj{}",obj);
        String shipName = JsonUtil.getJSONObjectString(obj,"shipName");
        String shipOwnerName = JsonUtil.getJSONObjectString(obj,"shipOwnerName");
        String  phoneNum = JsonUtil.getJSONObjectString(obj,"phoneNum");
        String tonnage = JsonUtil.getJSONObjectString(obj,"tonnage");
        String mmsi = JsonUtil.getJSONObjectString(obj,"mmsi");
        ShipOwnerDto shipOwnerDto = new ShipOwnerDto();
        ParamDto paramDto = new ParamDto();
        JSONObject jsonObject = new JSONObject();
        if (StringUtil.isNotEmpty(shipOwnerName) && StringUtil.isNotEmpty(phoneNum)){
            shipOwnerDto.setPhoneNum(phoneNum);
            shipOwnerDto.setShipOwnerName(shipOwnerName);
            ShipOwnerDto shipOwnerDto1 = iShipDao.selectShipOwner(shipOwnerDto);
            if (shipOwnerDto1 == null){
                iShipDao.insertShipOwner(shipOwnerDto);
            }
        }else{
            jsonObject.put("SUCCESS",false);
            jsonObject.put("MSG","船主电话和姓名不能为空！");
            return jsonObject;
        }
        ShipInfoDto shipInfoDto = new ShipInfoDto();
        if (StringUtil.isNotEmpty(shipName) && StringUtil.isNotEmpty(tonnage) && StringUtil.isNotEmpty(mmsi)){
            paramDto.setMmsi(mmsi);
            paramDto.setShipName(shipName);
            shipInfoDto.setShipName(shipName);
            shipInfoDto.setTonnage(Double.parseDouble(tonnage));
            shipInfoDto.setRenZhengState(0);
            shipInfoDto.setMonitoring(0);
            shipInfoDto.setMmsi(mmsi);
            shipInfoDto.setShipOwnerId(shipOwnerDto.getId());
            ShipInfoDto shipInfoDto1 = iShipDao.selectShipInfoByShipNameAndByMmsi(paramDto);
            if (shipInfoDto1 == null){
                iShipDao.insertShipInfo(shipInfoDto);
            }
        }else{
            jsonObject.put("SUCCESS",false);
            jsonObject.put("MSG","船名、吨位或mmsi不能为空！");
            return jsonObject;
        }
        jsonObject.put("SUCCESS",true);
        jsonObject.put("MSG","新增成功！");
        return jsonObject;
    }

    @Override
    public JSONObject selectShipInfosByShipId(HttpServletRequest request)throws Exception {
        JSONObject obj = JsonUtil.getJSONObject(request);
        logger.info("ShipServiceImpl selectShipInfosByShipId start obj{}",obj);
        String shipId = JsonUtil.getJSONObjectString(obj,"shipId");
        ParamDto paramDto = new ParamDto();
        if (StringUtil.isNotEmpty(shipId)){
            paramDto.setShipId(Integer.parseInt(shipId));
        }
        ShipInfoDto shipInfoDto = iShipDao.selectShipInfosByShipId(paramDto);
        JSONObject jsonObject = new JSONObject();
        if (shipInfoDto == null){
            jsonObject.put("SUCCESS",true);
            jsonObject.put("shipsList",null);
            jsonObject.put("shipsCount",0);
            jsonObject.put("MSG","没有该船舶信息！");
            return  jsonObject;
        }
        jsonObject.put("SUCCESS",true);
        jsonObject.put("shipInfoDto",shipInfoDto);
        return jsonObject;
    }

    @Override
    public JSONObject selectBeOverdueShipInfo(HttpServletRequest request) throws Exception {
        JSONObject obj = JsonUtil.getJSONObject(request);
        logger.info("ShipServiceImpl selectBeOverdueShipInfo start obj{}",obj);
        String page =JsonUtil.getJSONObjectString(obj,"page");
        String limit = JsonUtil.getJSONObjectString(obj,"limit");
        ParamDto param = new ParamDto();
        PageUtil.setPage(Integer.parseInt(page),Integer.parseInt(limit),param);
        param.setEndTime(new Timestamp((new Date()).getTime()));
        Integer companyId =  Integer.parseInt((String) request.getSession().getAttribute("SESSION_COMPANY_ID"));
        param.setUserId(companyId);
        // param.setUserId(1);
        param.setUsStatus(1);
        List<ShipInfoDto> shipInfoDtoList = iShipDao.selectBeOverdueShipInfo(param);
        int shipsCount = iShipDao.selectBeOverdueShipInfoCount(param);
        JSONObject jsonObject = new JSONObject();
        if(ListUtil.isEmpty(shipInfoDtoList)){
            jsonObject.put("SUCCESS",true);
            jsonObject.put("shipsList",null);
            jsonObject.put("shipsCount",0);
            jsonObject.put("MSG","查询数据为空！");
        }
        else {
            jsonObject.put("shipsList",shipInfoDtoList);
            jsonObject.put("shipsCount",shipsCount);
            jsonObject.put("SUCCESS",true);
        }
        return jsonObject;
    }

    /**
     * 1、吨位和出发地判断，不能同时为空，同时为空就不返回数据
     * 2、先判断是否有吨位，有则查出数据，数据为空直接返回不走后面逻辑，没有则查所有船舶数据
     * 3、判断是否有出发地，没有则返回1中的数据。有则和1中的数据进行判断，判断经纬度是否在出发地中，有则添加到最新的数据中返回。
     * @param request (dunWei吨位格式0-1000，chuFaDi出发地，格式左上经度，左上纬度-右上经度，右上纬度-右下经度，右下纬度-左下经度，左下纬度)
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject queryShipByLat(HttpServletRequest request) throws Exception {
        JSONObject obj = JsonUtil.getJSONObject(request);
        String dunWei = JsonUtil.getJSONObjectString2(obj,"dunWei");
        String chuFaDi = JsonUtil.getJSONObjectString2(obj,"chuFaDi");
        String isZY = JsonUtil.getJSONObjectString(obj,"isZY");
        logger.info("ShipServiceImpl queryShipByLat start obj{}",obj);

        if (StringUtil.isNotEmpty(isZY) && "Y".equals(isZY)) {
            //查询自有船舶
            Integer companyId =  Integer.parseInt((String) request.getSession().getAttribute("SESSION_COMPANY_ID"));
            return queryZYShip(companyId,chuFaDi);
        }
        else {
            //查询区域船舶
            return initAreaShip(dunWei,chuFaDi);
        }
    }

    @Override
    public JSONObject queryShipByName(HttpServletRequest request) throws Exception {
        JSONObject obj = JsonUtil.getJSONObject(request);
        String shipName = JsonUtil.getJSONObjectString2(obj,"shipName");
        return initQueryShipByName(shipName);
    }

    @Override
    public JSONObject selectShipTrack(HttpServletRequest request) throws Exception {
        JSONObject obj = JsonUtil.getJSONObject(request);
        logger.info("ShipServiceImpl selectBeOverdueShipInfo start obj{}",obj);
        String mmsi = JsonUtil.getJSONObjectString(obj,"mmsi");
        String timeSearch = JsonUtil.getJSONObjectString(obj,"timeSearch");
        ParamDto paramDto = new ParamDto();
        if (StringUtil.isNotEmpty(mmsi)){
            paramDto.setMmsi(mmsi);
        }
        if (StringUtil.isNotEmpty(timeSearch)){
            String startTime = timeSearch.split(" - ")[0];
            String endTime = timeSearch.split(" - ")[1];
            paramDto.setStartTime(DateUtil.strFormatTimetampTest(startTime));
            paramDto.setEndTime(DateUtil.strFormatTimetampTest(endTime));
        }

        JSONArray jsonArray = new JSONArray();
        List<ShipTrackDto> shipTrackDtoList = iShipDao.selectShipTrack(paramDto);
        for (int i = 0; i <shipTrackDtoList.size() ; i++) {
            JSONObject jsonObject = new JSONObject();
            shipTrackDtoList.get(i).setUpdate_Time(shipTrackDtoList.get(i).getUpdateTime().toString().substring(0,shipTrackDtoList.get(i).getUpdateTime().toString().indexOf(".")));
            jsonObject.put("name",shipTrackDtoList.get(i).getUpdate_Time());
            jsonObject.put("lnglat","["+shipTrackDtoList.get(i).getGLon()+","+shipTrackDtoList.get(i).getGLat()+"]");
            jsonArray.add(jsonObject);
        }
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("SUCCESS",true);
        jsonObject1.put("trackList",jsonArray);
        return jsonObject1;
    }


    //查询自有船舶
    public JSONObject queryZYShip(Integer companyId, String chuFaDi) throws Exception {
        ParamDto paramDto = new ParamDto();
        List<ShipInfoDto> shipInfoDtoList;
//        JSONObject retObj = new JSONObject();
        paramDto.setCompanyId(companyId);
//            paramDto.setCompanyId(4);
        paramDto.setEndTime(new Timestamp((new Date()).getTime()));
        shipInfoDtoList = iShipDao.queryAllZYShip(paramDto);
//
//        JSONArray retArr = new JSONArray();
//        if (ListUtil.isNotEmpty(shipInfoDtoList)) {
//            for (ShipInfoDto shipInfoDto : shipInfoDtoList) {
//                JSONObject jsonObject = new JSONObject();
//                getShipInfo(jsonObject, shipInfoDto);
//                retArr.add(jsonObject);
//            }
//        }
        return checkChuFaDi(chuFaDi,shipInfoDtoList);
    }

    //查询区域船舶
    private JSONObject initAreaShip(String dunWei,String chuFaDi) {
        JSONObject retObj = new JSONObject();
        List<ShipInfoDto> shipInfoDtoList;
        if (StringUtil.isEmpty(dunWei) && StringUtil.isEmpty(chuFaDi)) {
            retObj.put("shipList", new JSONArray());
            retObj.put("SUCCESS", false);
            retObj.put("MSG", "筛选条件为空");
            return retObj;
        }
        ParamDto param = new ParamDto();
        if (StringUtil.isNotEmpty(dunWei)) {
            String[] dunWeiArr = dunWei.split("-");
            param.setMinTonnage(Double.parseDouble(dunWeiArr[0]));
            param.setMaxTonnage(Double.parseDouble(dunWeiArr[1]));
            shipInfoDtoList = iShipDao.queryShip(param);
            if (ListUtil.isEmpty(shipInfoDtoList)) {
                retObj.put("shipList", new JSONArray());
                retObj.put("SUCCESS",true);
                return retObj;
            }
        }
        else {
            shipInfoDtoList = iShipDao.queryShip(param);
        }

        return checkChuFaDi(chuFaDi,shipInfoDtoList);
    }

    private JSONObject checkChuFaDi(String chuFaDi,List<ShipInfoDto> shipInfoDtoList) {
        JSONObject retObj = new JSONObject();
        JSONArray retArr = new JSONArray();
        if(StringUtil.isNotEmpty(chuFaDi)) {
            String[] chuFaDiArr = chuFaDi.split("-");
            if (4 != chuFaDiArr.length || StringUtil.isEmpty(chuFaDiArr[0].split(",")[0]) || "undefined".equals(chuFaDiArr[0].split(",")[0])) {
                logger.info("queryShipByLat 经纬度传错:{}",chuFaDi);
                retObj.put("MSG", "经纬度传错！");
                retObj.put("shipList", retArr);
                retObj.put("SUCCESS",false);
                return retObj;
            }
            double zsLon = Double.parseDouble(chuFaDiArr[0].split(",")[0]);
            double zsLat = Double.parseDouble(chuFaDiArr[0].split(",")[1]);
            double ysLon = Double.parseDouble(chuFaDiArr[1].split(",")[0]);
            double zxLat = Double.parseDouble(chuFaDiArr[3].split(",")[1]);
            for (ShipInfoDto shipInfoDto : shipInfoDtoList) {
                String gLat = shipInfoDto.getGLat();
                String gLon = shipInfoDto.getGLon();
                if (StringUtil.isNotEmpty(gLat) && StringUtil.isNotEmpty(gLon)) {
                    double latD = Double.parseDouble(gLat);
                    double lonD = Double.parseDouble(gLon);
                    if ((zsLon <= lonD && lonD <=ysLon) && (zxLat <= latD && latD <= zsLat)) {
                        JSONObject jsonObject = new JSONObject();
                        getShipInfo(jsonObject, shipInfoDto);
                        retArr.add(jsonObject);
                    }
                }
            }
        }
        else {
            for (ShipInfoDto shipInfoDto : shipInfoDtoList) {
                JSONObject jsonObject = new JSONObject();
                getShipInfo(jsonObject, shipInfoDto);
                retArr.add(jsonObject);
            }
        }
        retObj.put("shipList", retArr);
        retObj.put("SUCCESS", true);
        return retObj;
    }

    //船名找船
    private JSONObject initQueryShipByName(String shipName) {
        JSONArray retArr = new JSONArray();
        JSONObject retObj = new JSONObject();
        if (StringUtil.isEmpty(shipName) ) {
            retObj.put("shipList", retArr);
            retObj.put("SUCCESS", false);
            retObj.put("MSG", "筛选条件为空");
            return retObj;
        }
        ParamDto param = new ParamDto();
        param.setShipName(shipName);

        List<ShipInfoDto> shipInfoDtoList = iShipDao.queryShip(param);
        if (ListUtil.isNotEmpty(shipInfoDtoList)) {
            ShipInfoDto shipInfoDto = shipInfoDtoList.get(0);
            JSONObject jsonObject = new JSONObject();
            getShipInfo(jsonObject, shipInfoDto);
            retArr.add(jsonObject);
        }
        else {
            retObj.put("MSG","当前搜索的船舶尚未收录，您可以至定制运力付费添加船舶并长期监测");
            /*JSONObject queryShipObj = new JSONObject();
            queryShipObj.put("keyword", shipName);
            JSONObject retShipObj = ShipXyAPIUtil.queryManyShip(queryShipObj);
            if (retShipObj !=null){
                JSONArray retArr1 = JsonUtil.getJSONArray(retShipObj, "jsonArray");
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < retArr1.size(); i++) {
                    JSONObject jsonObject = retArr1.getJSONObject(i);
                    sb.append(jsonObject.getString("mmsi")).append(",");
                }
                if (sb.length() > 0) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("shipIds",sb.substring(0,sb.length() - 1));
                    JSONObject retShipInfoObj = ShipXyAPIUtil.getManyShip(jsonObject);
                    if (null != retShipInfoObj) {
                        getShipInfo(retArr, retShipInfoObj);
                    }
                }
            }*/
        }
        retObj.put("SUCCESS",true);
        retObj.put("shipList", retArr);
        return retObj;
    }


    private void getShipInfo(JSONObject jsonObject, ShipInfoDto shipInfoDto) {
        //船名
        jsonObject.put("shipName", shipInfoDto.getShipName());
        //吨位
        jsonObject.put("tonnage", shipInfoDto.getTonnage());
        //船长
        jsonObject.put("length", StringUtil.isEmpty(shipInfoDto.getLength()) ? "" : shipInfoDto.getLength());
        //船宽
        jsonObject.put("width", StringUtil.isEmpty(shipInfoDto.getWidth()) ? "" : shipInfoDto.getWidth());
        //吃水
        jsonObject.put("draught", StringUtil.isEmpty(shipInfoDto.getDraught()) ? "" : shipInfoDto.getDraught());
        //经度
        String gLon = shipInfoDto.getGLon();
        //纬度
        String gLat = shipInfoDto.getGLat();
        jsonObject.put("lon", StringUtil.isEmpty(gLon) ? "" :gLon);
        jsonObject.put("lat", StringUtil.isEmpty(gLat) ? "" : gLat);
//        jsonObject.put("lonZ", cacuLonLat(Double.parseDouble(gLon)));
//        jsonObject.put("latZ", cacuLonLat(Double.parseDouble(gLat)));
        //航迹向
        jsonObject.put("track", StringUtil.isEmpty(shipInfoDto.getCog()) ? "" : shipInfoDto.getCog());
        //船首向
        jsonObject.put("hdg", StringUtil.isEmpty(shipInfoDto.getHdg()) ? "" : shipInfoDto.getHdg());
        //速度，毫米/秒
        jsonObject.put("sog", StringUtil.isEmpty(shipInfoDto.getSog()) ? "" : shipInfoDto.getSog());
        //航行状态
        jsonObject.put("shipState", StringUtil.isEmpty(shipInfoDto.getNavistat()) ? "" : shipInfoDto.getNavistat());
        //目的地
        jsonObject.put("dest", StringUtil.isEmpty(shipInfoDto.getDestStd()) ? "" : shipInfoDto.getDestStd());
        //预计到港时间
        jsonObject.put("etaStd", StringUtil.isEmpty(shipInfoDto.getEtaStd()) ? "" : shipInfoDto.getEtaStd());
        //数据更新时间
        jsonObject.put("lastTime", StringUtil.isEmpty(shipInfoDto.getLastTime()) ? "" : shipInfoDto.getLastTime());
        //mmsi
        jsonObject.put("mmsi", shipInfoDto.getMmsi());
        //shipId
        jsonObject.put("shipId",shipInfoDto.getShipId());
        //船名
//        jsonObject.put("shipOwnerName", StringUtil.isEmpty(shipInfoDto.getShipOwnerName()) ? "" :shipInfoDto.getShipOwnerName());

    }

    private String cacuLonLat(double lonLat) {

        int degree = (int)lonLat;
        int min = (int)((lonLat - degree) * 60);
        int sec = (int)((lonLat - degree) * 3600 - min * 60);
        return "" + degree + '°' + min + '′' + sec + '″';
    }

}